package com.bootdo.system.service.impl;

import com.bootdo.common.domain.Tree;
import com.bootdo.common.service.CrudService;
import com.bootdo.common.utils.BuildTree;
import com.bootdo.system.dao.AreaDao;
import com.bootdo.system.domain.AreaDO;
import com.bootdo.system.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true)
public class AreaServiceImpl extends CrudService<AreaDao, AreaDO> implements AreaService {

	@Autowired
	private AreaDao areaDao;
	
	@Override
	public AreaDO get(String id){
		return areaDao.get(id);
	}
	
	@Override
	public List<AreaDO> list(Map<String, Object> map){
		return areaDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return areaDao.count(map);
	}
	
	@Override
	@Transactional(readOnly = true)
	public AreaDO saveArea(AreaDO area){
		return super.saveEntity(area);
	}
	
	@Override
	@Transactional(readOnly = true)
	public AreaDO updateArea(AreaDO area){
		return super.saveEntity(area);
	}
	
	@Override
	@Transactional(readOnly = true)
	public int remove(String id){
		return areaDao.remove(id);
	}
	
	@Override
	@Transactional(readOnly = true)
	public int batchRemove(String[] ids){
		return areaDao.batchRemove(ids);
	}

	@Override
	public Tree<AreaDO> getTree() {
		List<Tree<AreaDO>> trees = new ArrayList<Tree<AreaDO>>();
		List<AreaDO> sysAreas = areaDao.list(new HashMap<String,Object>(16));
		for (AreaDO sysArea : sysAreas) {
			Tree<AreaDO> tree = new Tree<AreaDO>();
			tree.setId(sysArea.getId());
			tree.setParentId(sysArea.getParentId());
			tree.setText(sysArea.getName());
			Map<String, Object> state = new HashMap<>(16);
			state.put("opened", true);
			tree.setState(state);
			trees.add(tree);
		}
		// 默认顶级菜单为０，根据数据库实际情况调整
		Tree<AreaDO> t = BuildTree.build(trees);
		return t;
	}
	
}
